<template>
  <div>
    <el-card v-if="showPage">
      <div class="title">账号设置</div>
      <el-form ref="form" :model="userForm" :rules="rules" label-width="80px" :hide-required-asterisk="true">
        <el-form-item prop="phone" label="手 机">
          <el-input :disabled="phoneFlag" class="input" v-model.trim="userForm.phone" size="small"></el-input>
          <el-button v-if="phoneFlag == true" @click="changeFlag('phone')" type="text">修改手机</el-button>
        </el-form-item>
        <el-form-item prop="password" v-if="phoneFlag == false">
          <el-input type="password" :disabled="phoneFlag" class="input" v-model.trim="userForm.password" size="small"
                    placeholder="请输入当前登录密码" show-password></el-input>
          <el-button v-if="phoneFlag == false" @click="changeInfo('phone')" type="danger" size="mini">确定</el-button>
          <el-button v-if="phoneFlag == false" @click="cancelUpdate('phone')" type="info" size="mini">取消</el-button>
        </el-form-item>
        <el-form-item prop="nickname" label="用户名">
          <el-input :disabled="nicknameFlag" class="input" v-model.trim="userForm.nickname" size="small"></el-input>
          <el-button v-if="nicknameFlag == true" @click="changeFlag('nickname')" type="text">修改用户名</el-button>
          <el-button v-if="nicknameFlag == false" @click="changeInfo('nickname')" type="danger" size="mini">确定</el-button>
          <el-button v-if="nicknameFlag == false" @click="cancelUpdate('nickname')" type="info" size="mini">取消</el-button>
        </el-form-item>
        <el-form-item prop="email" label="邮 箱">
          <el-input :disabled="emailFlag" class="input" v-model.trim="userForm.email" size="small"></el-input>
          <el-button v-if="emailFlag == true" @click="changeFlag('email')" type="text">修改邮箱</el-button>
          <el-button v-if="emailFlag == false" @click="changeInfo('email')" type="danger" size="mini">确定</el-button>
          <el-button v-if="emailFlag == false" @click="cancelUpdate('email')" type="info" size="mini">取消</el-button>
        </el-form-item>
        <el-form-item label="密 码">
          <el-input class="input" size="small" style="visibility: hidden"></el-input>
          <el-button type="text" @click="changeFlag('password')">修改密码</el-button>
        </el-form-item>
      </el-form>
      <!--修改密码对话框-->
      <el-dialog title="修改密码" :visible.sync="centerDialogVisible" width="25%" center>
        <el-form :model="pwdForm" :rules="pwdRules" :hide-required-asterisk="true">
          <el-form-item prop="oldPassword" label="输入旧密码">
            <el-input type="password" show-password class="dialog" clearable
                      v-model.trim="pwdForm.oldPassword" size="small"
                      placeholder="请输入旧密码">
            </el-input>
          </el-form-item>
          <el-form-item prop="newPassword" label="输入新密码">
            <el-input type="password" show-password class="dialog" clearable
                      v-model.trim="pwdForm.newPassword" size="small"
                      placeholder="请输入新密码">
            </el-input>
          </el-form-item>
          <el-form-item prop="newPassword2" label="确认新密码">
            <el-input type="password" show-password class="dialog" clearable
                      v-model.trim="pwdForm.newPassword2" size="small"
                      placeholder="请确认新密码">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelUpdatePwd" size="mini">取 消</el-button>
          <el-button type="primary" @click="updatePwd" size="mini">确 定</el-button>
        </span>
      </el-dialog>
      <div class="title">账号管理</div>
      <el-form :model="pwdForm" :rules="pwdRules" :hide-required-asterisk="true">
        <el-form-item label="账号注销" label-width="80px">
          <el-input class="input" size="small" style="visibility: hidden"></el-input>
          <el-button type="text" @click="LogOff()">立即注销</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
var phone = '';
var nickname = '';
var email = '';
// 手机号验证
const validPhone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
// 邮箱验证
const validEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;

export default {
  created() {
    this.getAllInfo();
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入新密码"));
      } else if (value.toString().length < 6 || value.toString().length > 32) {
        callback(new Error("密码长度为6-32位"));
      } else if (value == this.pwdForm.oldPassword) {
        callback(new Error("新密码不能与旧密码一致"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.pwdForm.newPassword) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      userForm: {
        id: '',
        phone: '',
        nickname: '',
        password: '',
        email: '',
      },
      rules: {
        phone: [
          {required: true, message: '请输入正确的手机号码', validator: this.validatePhone, trigger: 'change'}
        ],
        email: [
          {required: true, message: '请输入正确的邮箱', validator: this.validateEmail, trigger: 'change'}
        ],
      },
      phoneFlag: true,
      nicknameFlag: true,
      emailFlag: true,
      // 控制获得数据后再加载页面
      showPage: false,
      centerDialogVisible: false,
      // 修改密码
      pwdForm: {
        oldPassword: '',
        newPassword: '',
        newPassword2: ''
      },
      pwdRules: {
        oldPassword: [
          { required: true, message: "请输入旧密码", trigger: 'change' }
        ],
        newPassword: [
          { required: true, validator: validatePass, trigger: 'change' }
        ],
        newPassword2: [
          { required: true, validator: validatePass2, trigger: "change" }
        ]
      },
    }
  },
  methods: {
    // 修改按钮
    changeFlag(val) {
      if (val == "phone") {
        this.phoneFlag = false;
        this.nicknameFlag = true;
        this.emailFlag = true;
        this.cancelUpdate('nickname');
        this.cancelUpdate('email');
        return;
      }
      if (val == "nickname") {
        this.nicknameFlag = false;
        this.phoneFlag = true;
        this.emailFlag = true;
        this.cancelUpdate('phone');
        this.cancelUpdate('email');
        return;
      }
      if (val == "email") {
        this.emailFlag = false;
        this.phoneFlag = true;
        this.nicknameFlag = true;
        this.cancelUpdate('phone');
        this.cancelUpdate('nickname');
        return;
      }
      if (val == "password") {
        this.centerDialogVisible = true;
      }
    },
    // 取消按钮
    cancelUpdate(val) {
      if (val == "phone") {
        this.phoneFlag = true;
        this.userForm.phone = phone;
        this.userForm.password = '';
        return;
      }
      if (val == "nickname") {
        this.nicknameFlag = true;
        this.userForm.nickname = nickname;
        return;
      }
      if (val == "email") {
        this.emailFlag = true;
        this.userForm.email = email;
        return;
      }
    },
    // 确认按钮
    changeInfo(val) {
      if (val == "phone") {
        if (this.userForm.password == '') {
          this.$message.error("密码不能为空！");
          return;
        }
        if (this.userForm.phone == '') {
          this.$message.error("手机号不能为空！");
          return;
        }
        // 手机号没变
        if (this.userForm.phone == phone) {
          this.phoneFlag = true;
          // 可能乱输入了密码
          this.userForm.password = '';
          return;
        }
        // 验证手机号码合法性
        if (!validPhone.test(this.userForm.phone)) {
          this.$message.error("请输入有效的手机号码！");
          return;
        }
        // 修改手机号码
        let queryInfo = this.$qs.stringify({
          phone: this.userForm.phone,
          password: this.userForm.password,
        });
        // console.log(queryInfo);
        // 判断是否登录超时，超时取消操作并跳转登录页
        if (!this.$cookies.isKey("status")) {
          // 销毁登录信息的cookie
          this.$cookies.remove("loginInfo");
          // 更新登录状态码为未登录状态
          this.$cookies.set("loginStatus", -2,0);
          this.$router.push("/login");
          this.$message.warning("修改失败，登录已超时，请重新登陆！");
          return;
        }
        this.$axios.put('/awareness/api/common/user/phone', queryInfo).then(res => {
          // console.log(res);
          if (res.data.status.code == -7) {
            this.$message.error("密码错误，请重新输入！");
            return;
          }
          // 修改成功设置更新登录cookie的手机号
          // this.$cookies.set("loginInfo", this.userForm.phone,0);
          // 重新获取数据
          this.getAllInfo();
          // this.$message.success("修改成功！");
          // 关闭修改状态
          this.phoneFlag = true;
          // 退出登录
          setTimeout(()=>{
            this.logout();
            //延迟时间：1秒
          },1000)
        }).catch( err => {

        });
        return;
      }

      if (val == "nickname") {
        if (this.userForm.nickname == '') {
          this.$message.error("用户名不能为空！");
        }
        // 用户名没变
        if (this.userForm.nickname == nickname) {
          this.nicknameFlag = true;
          return;
        }
        // 修改用户名
        let queryInfo = this.$qs.stringify({
          id: this.userForm.id,
          phone: this.userForm.phone,
          nickname: this.userForm.nickname,
          email: this.userForm.email
        });
        // 判断是否登录超时，超时取消操作并跳转登录页
        if (!this.$cookies.isKey("status")) {
          // 销毁登录信息的cookie
          this.$cookies.remove("loginInfo");
          // 更新登录状态码为未登录状态
          this.$cookies.set("loginStatus", -2,0);
          this.$router.push("/login");
          this.$message.warning("修改失败，登录已超时，请重新登陆！");
          return;
        }
        // console.log(queryInfo);
        this.$axios.put('/awareness/api/user/info', queryInfo).then(res => {
          // console.log(res);
          // 重新获取数据
          this.getAllInfo();
          // this.$message.success("修改成功！");
          // 关闭修改状态
          this.nicknameFlag = true;
          setTimeout(()=>{
            this.logout();
            //延迟时间：1秒
          },1000)
        }).catch( err => {

        });
        return;
      }

      if (val == "email") {
        if (this.userForm.email == '') {
          this.$message.error("邮箱不能为空！");
        }
        // 邮箱没变
        if (this.userForm.email == email) {
          this.emailFlag = true;
          return;
        }
        // 验证邮箱合法性
        if (!validEmail.test(this.userForm.email)) {
          this.$message.error("请输入有效的邮箱！");
          return;
        }
        // 修改邮箱
        let queryInfo = this.$qs.stringify({
          id: this.userForm.id,
          phone: this.userForm.phone,
          nickname: this.userForm.nickname,
          email: this.userForm.email
        });
        // 判断是否登录超时，超时取消操作并跳转登录页
        if (!this.$cookies.isKey("status")) {
          // 销毁登录信息的cookie
          this.$cookies.remove("loginInfo");
          // 更新登录状态码为未登录状态
          this.$cookies.set("loginStatus", -2,0);
          this.$router.push("/login");
          this.$message.warning("修改失败，登录已超时，请重新登陆！");
          return;
        }
        // console.log(queryInfo);
        this.$axios.put('/awareness/api/user/info', queryInfo).then(res => {
          // console.log(res);
          // 重新获取数据
          this.getAllInfo();
          this.$message.success("修改成功！");
          // 关闭修改状态
          this.emailFlag = true;
        }).catch( err => {

        });
        return;
      }
    },
    // 修改密码
    updatePwd() {
      if (this.pwdForm.oldPassword == '' || this.pwdForm.newPassword == '' || this.pwdForm.newPassword2 == '') {
        this.$message.error("密码不能为空");
        return;
      }
      if (this.pwdForm.newPassword != this.pwdForm.newPassword2) {
        this.$message.error("两次输入的密码不一致！");
        return;
      }
      // 新密码与原密码一致禁止修改
      if (this.pwdForm.newPassword == this.pwdForm.oldPassword) {
        this.$message.error("新密码不能与原密码一致！");
        return;
      }
      let queryInfo = this.$qs.stringify({
        beforePass: this.pwdForm.oldPassword,
        afterPass: this.pwdForm.newPassword,
      });
      // console.log(queryInfo);
      // 判断是否登录超时，超时取消操作并跳转登录页
      if (!this.$cookies.isKey("status")) {
        // 销毁登录信息的cookie
        this.$cookies.remove("loginInfo");
        // 更新登录状态码为未登录状态
        this.$cookies.set("loginStatus", -2,0);
        this.$router.push("/login");
        this.$message.warning("修改失败，登录已超时，请重新登陆！");
        return;
      }
      this.$axios.put('/awareness/api/common/user/pass', queryInfo).then(res => {
        // console.log(res);
        if (res.data.status.code == -8) {
          this.$message.error("旧密码错误，请重新输入！");
          return;
        }
        // this.$message.success("修改成功！");
        // 退出登录
        setTimeout(()=>{
          this.logout();
          //延迟时间：1秒
        },1000)
      }).catch( err => {

      });
    },
    // 取消修改密码
    cancelUpdatePwd() {
      this.centerDialogVisible =  false;
      this.pwdForm.oldPassword = '';
      this.pwdForm.newPassword = '';
      this.pwdForm.newPassword2 = '';
    },
    // 获取当前用户信息
    getAllInfo() {
      var queryPhone = this.$cookies.get("loginInfo");
      this.$axios.get('/awareness/api/user/info',{
        params:{
          phone: queryPhone
        }
      }).then(res => {
        // console.log(res);
        this.userForm.id = res.data.result.data[0].id;
        this.userForm.phone = res.data.result.data[0].phone;
        this.userForm.nickname = res.data.result.data[0].nickname;
        this.userForm.email = res.data.result.data[0].email;
        phone = res.data.result.data[0].phone;
        nickname = res.data.result.data[0].nickname;
        email = res.data.result.data[0].email;
        this.showPage = true;
      }).catch( err => {

      });
    },
    // 注销账号
    LogOff() {
      this.$confirm('此操作将注销你的账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 判断是否登录超时，超时取消操作并跳转登录页
        if (!this.$cookies.isKey("status")) {
          // 销毁登录信息的cookie
          this.$cookies.remove("loginInfo");
          // 更新登录状态码为未登录状态
          this.$cookies.set("loginStatus", -2,0);
          this.$router.push("/login");
          this.$message.warning("注销失败，您的登录已超时，请重新登陆！");
          return;
        }
        // 执行注销账号操作
        var deleteId = this.userForm.id;
        this.$axios.delete(`/awareness/api/user/info/${deleteId}`)
            .then(res=>{
              // console.log(res);
              // 注销成功退出登录
              this.logout();
            })
        this.$message.success("您的账号已注销！")
      }).catch(() => {

      });
    },
    // 退出登录
    logout() {
      this.$axios.get('/awareness/api/common/logout')
          .then(res => {
            // console.log(res);
            if (res.data.status.code == 1){
              // 销毁登录信息的cookie
              this.$cookies.remove("loginInfo");
              // 更新登录状态码为未登录状态
              this.$cookies.set("loginStatus", -2,0);
              this.$router.push("/login");
              // this.$message.success('已退出登录！');
            }
          })
          .catch( err => {});
    },
    /**
     * 验证手机号是否正确
     * @param rule
     * @param value
     * @param callback
     */
    validatePhone(rule, value, callback) {
      if ((!validPhone.test(value)) && value !== ''){
        callback(new Error('请输入正确的手机号码'));
      } else if( !value) {
        callback();
      }
    },
    /**
     * 验证邮箱是否正确
     * @param rule
     * @param value
     * @param callback
     */
    validateEmail(rule, value, callback) {
      if ((!validEmail.test(value)) && value !== ''){
        callback(new Error('请输入正确的邮箱'));
      } else if( !value) {
        callback();
      }
    },
  }
}
</script>

<style scoped>
.input {
  width: 20%;
  margin-right: 20px;
}
.dialog {
  width: 65%;
}
.title {
  font-size: 1.17em;
  font-weight: bold;
  margin-bottom: 10px;
}
/deep/ .el-dialog--center .el-dialog__body {
  text-align: center;
  padding: 10px 15px 0px 30px;
}
</style>